//出库未安装 原因
public with sharing class OutdoorNotInstallController {

	public String backId {get; private set;} 
	public String msg {get; private set;} 
	public Boolean isErr {get; private set;} 
	public String dataJson {get; private set;} 
	public String saveJson {get;  set;} 
	public Boolean isSuccess {get ; private set;}
	public String selectProductId {get ; set;}

	public String unusecombobox {get; private set;}
    public String uninstallcombox {get; private set;}

    public OutdoorNotInstallController() {
        
    }


    public void  init(){

    	Map<String ,Object> dataMap = new Map<String,Object>();
    	//dataMap.put('install',getDetails());
    	//dataMap.put('equip',getEquipDetails());
    	dataMap.put('options',getProductsMap());
        dataMap.put('ina_options',getInstallProductMap());
        dataMap.put('statuscombox', ImportObject.getPicklistValues('Equipment__c', 'OpponentStatus__c', true));
    	dataMap.put('unusecombobox', ImportObject.getPicklistValues('Equipment__c', 'UnusedCause__c', true));
        dataMap.put('uninstallcombox', ImportObject.getPicklistValues('InstallationApply__c', 'ReasonsNotInstalling__c', true));
        dataMap.put('combinestatuscombox', ImportObject.getPicklistValues('CombinationForm__c', 'OpponentStatus__c', true));
    	dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap),'UTF-8');

    }




    public List<Object> getInstallProductMap(){
        //品牌等于maccura或者加斯戴克
        List<Object> combobos = new List<Object>();
        for(AggregateResult arg : [select Instrument__c , Instrument__r.Name from InstallationApply__c  
            where Instrument__c  != null  and Instrument__r.Brand__c in ('maccura','加斯戴克')
              group by Instrument__c, Instrument__r.Name ]){
            Map<String,String> combo = new Map<String,String>();

            combo.put('id', (String)arg.get('Instrument__c'));
            combo.put('text',(String) arg.get('Name'));
            combobos.add(combo);
        }
        return combobos;

    }
    public List<Object> getProductsMap(){

    	List<Object> combobos = new List<Object>();
		for(AggregateResult arg : [select Instrument__r.Product__c , 
              Instrument__r.Product__r.Name from 
              InstrumentProjectOverview__c  where Instrument__r.Product__c  != null 
              group by Instrument__r.Product__c, Instrument__r.Product__r.Name   ]){
			Map<String,String> combo = new Map<String,String>();
			combo.put('id', (String)arg.get('Product__c'));
			combo.put('text',(String) arg.get('Name'));
			combobos.add(combo);

		}

		return combobos;

    }

    public void  getCombinationForm(){

        List<Object> tmp = new List<Object>();

        for(CombinationForm__c cf : [select Id,Name,Customer__c,Customer__r.Name ,CombinationForm__c,DutyOfficer__c, OpponentStatus__c from CombinationForm__c where OpponentStatus__c=:selectProductId ]){

            tmp.add(new CombineBean(cf));
        }
        dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');

    }

    //获取未使用的仪器
    public  void getEquipDetails(){
    	List<InstallBean>tmp = new List<InstallBean>();
    	if(selectProductId  != null){

    		for ( Equipment__c e : [select Id,DutyOfficer__c,OpponentStatus__c,Product__r.Name ,Supplier__c,Supplier__r.Name ,Account__r.Name , Name ,Solution__c, UnusedCause__c, Remarks__c,IMEINumber__c,
    			(select Id,UsageType__c,TS__c,Items__c,Status__c  from InstrumentProjectOverview__r )
    		 from Equipment__c where OpponentStatus__c in ('安装未使用','使用后停用') and  Type__c = null   
             and Product__c =:selectProductId and Account__r.RecordType.DeveloperName != 'Maccura' and (not  Account__r.Name like  '%迈克测试%') 
             Order by  OpponentStatus__c , Account__c desc ]) {
    			tmp.add(new InstallBean(e,null));
    			
    		}
    	}

    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');
    	//return tmp;
    }
    

    //获取正常使用的仪器的仪器项目
    public  void getEquipProjectDetails(){
    	List<InstallBean>tmp = new List<InstallBean>();
    	//组装动态表格
    	//表头 第一行

	    Set<String> itemset = new Set<String>();

    	if(selectProductId  != null){

    		//获取仪器项目
    		

    		for ( Equipment__c e : [select Id,DutyOfficer__c ,OpponentStatus__c,Product__r.Name ,Supplier__c,Supplier__r.Name ,Account__r.Name , Name ,Solution__c, UnusedCause__c, Remarks__c,IMEINumber__c,
    			(select Id,UsageType__c,TS__c,Items__c,Status__c  from InstrumentProjectOverview__r where Items__c != null  )
    		 from Equipment__c where OpponentStatus__c = '正常使用'  and Product__c =:selectProductId  
             and Account__r.RecordType.DeveloperName != 'Maccura' and (not  Account__r.Name like  '%迈克测试%') and  Type__c = null  ]) {
    				
    				List<ProjectBean> ptmp = new List<ProjectBean>();
    				for (InstrumentProjectOverview__c ipo  : e.InstrumentProjectOverview__r ) {
    					if(ipo.Items__c == null )continue;
    					itemset.add(ipo.Items__c);

    					ptmp.add(new ProjectBean(ipo));

    				}
    			tmp.add(new InstallBean(e,ptmp));
    			
    		}

    	}
        System.debug(tmp);
    	Map<String,Object> dataMap = new Map<String,Object>();
    	dataMap.put('data',tmp);
    	dataMap.put('items',itemset);
    	dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap),'UTF-8');
    	//return tmp;
    }


  
    /*public List<InstallBean> getEquipDetails(){

    	List<InstallBean>tmp = new List<InstallBean>();
    	for (Equipment__c e  : [select Id ,Product__r.Name,Account__c ,Account__r.Name,Remarks__c,UnusedCause__c,Solution__c 
    		from Equipment__c where OpponentStatus__c = '安装未使用' ] ) {
    		tmp.add(new InstallBean(e));

    	}
    	return tmp ; 
    }*/
    //获取出库未安装原因 及解决方案
    public void  getDetails(){

    	List<InstallBean>tmp = new List<InstallBean>();
    	if(selectProductId  != null){
    		for (InstallationApply__c insa  : [select Id,Hospital__r.Name,Instrument__c,Instrument__r.Name ,FuselageNumber__c,

    		 ReasonsNotInstalling__c,NotesNotInstalled__c,Solution__c ,InstallInstruments__r.FuselageNumber__c,NEWDealer__c,NEWDealer__r.Name 

    		from InstallationApply__c where ActualDepotTime__c != null and  RelatedWorkOrder__c = null  and Instrument__c =:selectProductId 
            and Hospital__r.RecordType.DeveloperName != 'Maccura' and (not  Hospital__r.Name like  '%迈克测试%') ] ) {
	    		tmp.add(new InstallBean(insa));

	    	}
    	}
    	

    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');

    	
    }
    public void setNil(){

    	dataJson  = '[]';
    	saveJson = '[]';
    	
    }

    public void combineSave(){
         msg = '';
        List<Object> saveList = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));

        List<CombinationForm__c>eqList = new List<CombinationForm__c>();

        for (Object  o  : saveList) {
            Map<String,Object>mo = (Map<String,Object>)o;
            CombinationForm__c eq = new CombinationForm__c();
            eq.id = DataUtil.getStringValue(mo.get('id'));
            eq.OpponentStatus__c = DataUtil.getStringValue(mo.get('status'));
            eq.DutyOfficer__c = DataUtil.getStringValue(mo.get('dutyoffice'));

            eqList.add(eq);

        }

        SavePoint sp = Database.setSavepoint();
        try {
            
            if(eqList.size()> 0) ControllerUtil.updateData(eqList) ; //update ;
            isSuccess = true ; 
            msg = '保存成功!';
        }
        catch (Exception e) {
            Database.rollback(sp);
            msg = '保存失败:'+e.getMessage();

        }

    }
    public void equipProjectSave(){
         msg = '';
    	Map<String,Object> saveMap  = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));

    	List<InstrumentProjectOverview__c>eqList = new List<InstrumentProjectOverview__c>();
        Map<Id,Equipment__c> eqMap = new Map<Id,Equipment__c>();
        List<Object> saveList = (List<Object>)saveMap.get('details');

    	for (Object  o  : saveList) {
    		Map<String,Object>mo = (Map<String,Object>)o;
    		InstrumentProjectOverview__c eq = new InstrumentProjectOverview__c();
            System.debug('equipProjectSave==>'+mo);

    		eq.Id = DataUtil.getStringValue(mo.get('id'));
    		if(eq.Id == null ) eq.Instrument__c = DataUtil.getStringValue(mo.get('eid'));

    		eq.TS__c =  DataUtil.getDecimalValue(mo.get('ts'));
    		eq.Items__c =  DataUtil.getStringValue(mo.get('name'));
    		eq.UsageType__c =  DataUtil.getStringValue(mo.get('type'));
    		eqList.add(eq);

    	}
        List<Object> eList = (List<Object>)saveMap.get('equips');
        for (Object  o  : eList) {
            Map<String,Object>mo = (Map<String,Object>)o;
            String eid = DataUtil.getStringValue(mo.get('id'));
            if(eid != null && (mo.get('supplier') != null || mo.get('status') != null ))eqMap.put(eid, new Equipment__c(Id =eid,Supplier__c=DataUtil.getStringValue(mo.get('supplier')),OpponentStatus__c= DataUtil.getStringValue(mo.get('status')),DutyOfficer__c = DataUtil.getStringValue(mo.get('dutyoffice'))));
        }

    	SavePoint sp = Database.setSavepoint();
    	try {
    	    
    	    if(eqList.size()> 0) ControllerUtil.upsertData(eqList) ;//upsert ;
            if(!eqMap.isEmpty())ControllerUtil.updateData(eqMap.values());
    	    isSuccess = true ; 
    	    msg = '保存成功!';
    	}
    	catch (Exception e) {
    		Database.rollback(sp);
    	    msg = '保存失败:'+e.getMessage();

    	}


    }
    public void equipSave(){

        msg = '';
    	List<Object> saveList = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));

    	List<Equipment__c>eqList = new List<Equipment__c>();

    	for (Object  o  : saveList) {
    		Map<String,Object>mo = (Map<String,Object>)o;
    		Equipment__c eq = new Equipment__c();
    		eq.id = DataUtil.getStringValue(mo.get('id'));
    		eq.Remarks__c =  DataUtil.getStringValue(mo.get('note'));
    		eq.UnusedCause__c =  DataUtil.getStringValue(mo.get('reason'));
    		eq.Solution__c =  DataUtil.getStringValue(mo.get('solution'));
            eq.Supplier__c = DataUtil.getStringValue(mo.get('supplier'));
            eq.OpponentStatus__c= DataUtil.getStringValue(mo.get('status'));
            eq.DutyOfficer__c = DataUtil.getStringValue(mo.get('dutyoffice'));

    		eqList.add(eq);

    	}

    	SavePoint sp = Database.setSavepoint();
    	try {
    	    
    	    if(eqList.size()> 0) ControllerUtil.updateData(eqList) ; //update ;
    	    isSuccess = true ; 
    	    msg = '保存成功!';
    	}
    	catch (Exception e) {
    		Database.rollback(sp);
    	    msg = '保存失败:'+e.getMessage();

    	}


    }


    public void save(){

    	List<Object> saveList = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));

    	List<InstallationApply__c>inList = new List<InstallationApply__c>();

    	for (Object  o  : saveList) {
    		Map<String,Object>mo = (Map<String,Object>)o;
    		InstallationApply__c insa = new InstallationApply__c();
    		insa.id = DataUtil.getStringValue(mo.get('id'));
    		insa.NotesNotInstalled__c =  DataUtil.getStringValue(mo.get('note'));
    		insa.ReasonsNotInstalling__c =  DataUtil.getStringValue(mo.get('reason'));
    		insa.Solution__c =  DataUtil.getStringValue(mo.get('solution'));
    		inList.add(insa);

    	}

    	SavePoint sp = Database.setSavepoint();
    	try {
    	    
    	    if(inList.size()> 0) ControllerUtil.updateData(inList) ;
    	    isSuccess = true ; 
    	    msg = '保存成功!';
    	}
    	catch (Exception e) {
    		Database.rollback(sp);
    	    msg = '保存失败:'+e.getMessage();

    	}
    	
    }

    public class CombineBean{
        public String id;
        public String name ; 
        public String accName ;
        public String status;
        public String type ; 
        public String dutyoffice ; 

        public CombineBean(CombinationForm__c cf ){

            id = cf.Id;
            name = cf.Name;
            accName = cf.Customer__r.Name;
            status = cf.OpponentStatus__c;
            type = cf.CombinationForm__c;
            dutyoffice = cf.DutyOfficer__c;


        }
    }
    public class ProjectBean{
    	public String id;
    	public String  name ;
    	public String type  ; 
    	public Decimal ts;
    	public ProjectBean(InstrumentProjectOverview__c ipo )  {
    		id = ipo.Id;
    		name = ipo.Items__c;
    		type = ipo.UsageType__c;
    		ts = ipo.TS__c;
    	}

    }

    public class InstallBean{

    	public String id; 
    	public String productName ; 
    	public String note;
    	public String reason ; 
    	public String solution ; 
    	public String accName ;
    	public String eno; 
    	public String status ;
    	public List<ProjectBean> details ;

        public String supplier;
        public String oldsupplier;
        public String oldstatus;
        public String supplierName;
        public String dutyoffice ; 


    	public InstallBean(InstallationApply__c insa ){
    		id = insa.Id ; 
    		productName = insa.Instrument__r.Name ; 
    		note = insa.NotesNotInstalled__c;
    		eno = insa.FuselageNumber__c == null ? insa.InstallInstruments__r.FuselageNumber__c  : insa.FuselageNumber__c ;
    		reason = insa.ReasonsNotInstalling__c;
    		solution = insa.Solution__c;
    		accName = insa.Hospital__r.Name ;
            supplierName = insa.NEWDealer__r.Name;
            supplier = insa.NEWDealer__c ;


    	}
    	public InstallBean(Equipment__c eq,List<ProjectBean> d ){

    		id = eq.Id ; 
    		eno = eq.IMEINumber__c;
    		productName = eq.Product__r.Name ; 
    		note = eq.Remarks__c;
    		reason = eq.UnusedCause__c;
    		solution = eq.Solution__c;
    		accName = eq.Account__r.Name ;
    		status = eq.OpponentStatus__c;
            oldstatus = eq.OpponentStatus__c;
            details = d;
            oldsupplier = eq.Supplier__c; 
    		supplierName = eq.Supplier__r.Name;
            supplier = eq.Supplier__c ;
            dutyoffice = eq.DutyOfficer__c ;

    	}

    }



}